package utils.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 模拟一个下载文件的接口以供测试
 */
public class DownloadServlet extends HttpServlet {

    private static final long serialVersionUID = 7027393739066329717L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String token = request.getParameter("token");
        if(token.equals("1"))
        {
            response.setContentType("application/x-msdownload");
//            String filePath="/home/zyk/test.log";
            String filePath="E:/1.txt";
            File file=new File(filePath);
            //解决乱码问题
            String filename=URLEncoder.encode(file.getName(),"utf-8");
            //重置输出流
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename="+filename);//设置文件名
            response.setContentType("application/octet-stream");//设置文件类型
            OutputStream toClient=new BufferedOutputStream(response.getOutputStream() );//获取二进制输出流
            //读取文件数据
            InputStream fis=new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer=new byte[4048];
            int size = 0;
            int len = 0;
            while ((size = fis.read(buffer)) != -1) {
                len += size;
                toClient.write(buffer, 0, size);
//                buf = new byte[1024];
                // 打印下载百分比
//                 System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
            }
            //输出文件数据
            toClient.close();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
